package bobaini.com.interceptor;

import bobaini.com.annotation.Token;
import bobaini.com.annotation.TokenNotValidation;
import bobaini.com.domain.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author: liuyi
 * ClassName: Test
 * Version: 1.0.0
 * DateTime: 2021/03/31-10:36:00
 * Description: TODO
 */
@Component
@Slf4j
public class AuthorityIntercept extends HandlerInterceptorAdapter {
    public static final String USER_KEY = "USER_ID";
    public static final String USER_INFO = "USER_INFO";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        Token annotation;
//        if (handler instanceof HandlerMethod) {
//            annotation = ((HandlerMethod) handler).getMethodAnnotation(Token.class);
//        } else {
//            return true;
//        }
//        //没有声明需要权限
//        if (annotation == null || annotation.validate() == false) {
//            return true;
//        }


        TokenNotValidation tokenNotValidation;
        if (handler instanceof HandlerMethod) {
            tokenNotValidation = ((HandlerMethod) handler).getMethodAnnotation(TokenNotValidation.class);
        } else {
            return true;
        }
        //声明就不需要权限
        if (tokenNotValidation != null) {
            return true;
        }


        //从header中获取token
        String token = request.getHeader("token");
        if (token == null) {
            log.info("缺少token，拒绝访问");
            return false;
        }

        /**
         * token校验通过，将用户信息放在request中，供需要用user信息的接口里从token取数据
         */
        request.setAttribute(USER_KEY, "123456");
        User user = new User();
        user.setId(10000L);
        user.setUserName("2118724165@qq.com");
        user.setPhoneNumber("15702911111");
        user.setToken(token);
        request.setAttribute(USER_INFO, user);
        return true;
    }
}
